#include "TFSettlementHandler.h"
#include <msgcenter/TFMsgProcess.h>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <core/Utility.h>

bool TFSettlementHandler::processCmd(const QJsonObject& cmdObj, const ReqInfo& reqinfo, bool unReg /*= false*/)
{
	if (!parseCmd(cmdObj))
		return false;

	qb::SSRequestMsg msg;
	msg.m_FuncID = E_FID_TF_SETTLEMENT_PRICE_REQ;
	msg.m_pRequest = &m_req;
	MessagePoster poster(&msg, qbmsg::tf::EncodeFunc);
	poster.send(this);

	m_reqInfo = reqinfo;
	return true;
}

void TFSettlementHandler::onDataArrived(const qb::SSAckMsg& msg)
{
	const xQBTfSettlementPriceAck* pData = static_cast<xQBTfSettlementPriceAck*>(msg.m_pRet);
	if (!pData)
		return;

	QJsonArray jsList;
	QJsonObject jsRes;
	int count = 0;
	for (const auto& item : pData->m_List)
	{
		if(!m_ReqAll && m_IdList.find(item.m_Id) == m_IdList.end())
			continue;

		QJsonObject jsItem;
		jsItem["id"] = item.m_Id;
		jsItem["time"] = item.m_Time;
		jsItem["settlement"] = item.m_SettPrice;
		jsList.append(jsItem);

		if (++count % 20 == 0)
		{
			jsRes["finish"] = 0;
			jsRes["list"] = jsList;

			QJsonDocument doc(jsRes);
            emit sendDataToWeb(m_reqInfo.m_frameId, m_reqInfo.m_sid, doc.toJson(QJsonDocument::Compact), m_reqInfo.m_jsCb);

			QJsonObject emptyObj;
			QJsonArray emptyArr;
			jsRes.swap(emptyObj);
			jsList.swap(emptyArr);
		}
	}

	jsRes["finish"] = 1;
	jsRes["list"] = jsList;

	QJsonDocument doc(jsRes);
    emit sendDataToWeb(m_reqInfo.m_frameId, m_reqInfo.m_sid, doc.toJson(QJsonDocument::Compact), m_reqInfo.m_jsCb);
}

bool TFSettlementHandler::parseCmd(const QJsonObject& cmdObj)
{
	QJsonObject condObj = cmdObj["cond"].toObject();
	if (condObj.isEmpty())
		return false;

	std::string stDate = condObj["startdate"].toString().toUtf8().data();
	std::string endDate = condObj["enddate"].toString().toUtf8().data();
	if (stDate.empty() || endDate.empty())
		return false;

	FIELDCOPY(m_req.m_Start, stDate.c_str());
	FIELDCOPY(m_req.m_End, endDate.c_str());

	QJsonArray jsList = condObj["list"].toArray();
	if (jsList.isEmpty())
	{
		m_ReqAll = true;
		return true;
	}

	for (const auto& obj : jsList)
	{
		std::string id = obj.toObject()["id"].toString().toUtf8().data();
		if(id.empty() || strlen(getTfKey(id.c_str())) == 0)
			continue;
		m_IdList.insert(id);
	}

	return true;
}
